package com.ymfNetty.server.handler;

import com.ymfNetty.message.GroupCreateRequestMessage;
import com.ymfNetty.message.GroupCreateResponseMessage;
import com.ymfNetty.server.session.Group;
import com.ymfNetty.server.session.GroupSession;
import com.ymfNetty.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if(group == null){
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, groupName+"群创建成功"));
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入" + groupName));
            }

        }else{
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "群创建失败，群聊已存在"));
        }

    }
}
